import upload from '@/common/upload/upload.js'
import $store from '@/store/index.js';
import msgSqlite from "@/sqlite_services/msg.js"
export default {
	/* 发送消息转义 */
	async send(data,chat_type) {
		let updata = null
		const sendFunction = typeFunction[data.msg_type];
		try {
			if (sendFunction && typeof sendFunction === 'function') {
				updata = await sendFunction(data); // 调用对应的发送函数，并传递数据
			}
			let res = null
			if(chat_type == 'private'){
				//私聊实现
				res = await uni.$api.chat.PrivateMsgSend(updata)
			}else if(chat_type == 'group'){
				//群聊实现
				res = await uni.$api.chat.GroupMsgSend(updata)
			}
			if(res){
				if($store.state.chat.chatInfo && data.target_id == $store.state.chat.chatInfo.uuid){
					uni.$emit('onMessageControls', {
						type:'send',
						data:{
							server:res.data,
							updata:updata,
							local_id:data.local_id
						}
					})
				}
				//发送成功更新消息数据库
				msgSqlite.updateMessageById(data.local_id, {
					msg_id: res.data.msg_id,
					msg_status: 'unread',
					conversation_id: res.data.conversation_id,
					content_text: updata.content_text
				})
				//更新会话列表
				$store.dispatch('updateSession', {
					chat_id: data.target_id,
					data: {
						last_msg_id: res.data.msg_id,
						conversation_id: res.data.conversation_id
					}
				})
				//返回到页面
				return {
					server:res.data,
					updata:updata,
					local_id:data.local_id
				}
			}else{
				msgSqlite.updateMessageById(data.local_id, {
					msg_status: 'failed'
				})
				uni.$emit('onMessageControls', {
					type:'send',
					data:{
						local_id:data.local_id
					}
				})
				throw res;
			}
		} catch (e) {
			msgSqlite.updateMessageById(data.local_id, {
				msg_status: 'failed'
			})
			
			uni.$emit('onMessageControls', {
				type:'send',
				data:{
					local_id:data.local_id
				}
			})
			throw e;
		}
	},
	/* 发送消息直接发 */
	async directsend(data,chat_type) {
		let updata = JSON.parse(JSON.stringify(data))
		updata.content_text = JSON.stringify(updata.content_text)
		try {
			let res = null
			if(chat_type == 'private'){
				//私聊实现
				res = await uni.$api.chat.PrivateMsgSend(updata)
			}else if(chat_type == 'group'){
				//群聊的未实现
				res = await uni.$api.chat.GroupMsgSend(updata)
			}
			if(res){
				return {
					server:res.data,
					updata:updata
				}
			}else{
				throw res;
			}
		} catch (e) {
			throw e;
		}
	},
	/* 不分群聊私聊撤回消息，直接删就行 */
	async withdraw(msg_id,target_id,chat_type) {
		try {
			if(chat_type == 'private'){
				let res = await uni.$api.chat.PrivateWithdraw({msg_id,target_id})
				if(res){
					return true
				}else{
					throw res;
				}
			}else if(chat_type == 'group'){
				let res = await uni.$api.chat.GroupWithdraw({msg_id,target_id})
				if(res){
					return true
				}else{
					throw res;
				}
			}
		} catch (e) {
			throw e;
		}
	},
	/* 删除消息 */
	async delmsg({target_id,msg_ids,del_msg_type,conversation_id},chat_type){
		try {
			if(chat_type == 'private'){
				let res = await uni.$api.chat.PrivateDelmsg({target_id,msg_ids,del_msg_type,conversation_id})
				if(res){
					return true
				}else{
					throw res;
				}
			}else if(chat_type == 'group'){
				//群聊的未实现
				let res = await uni.$api.chat.GroupDelmsg({target_id,msg_ids,del_msg_type,conversation_id})
				if(res){
					return true
				}else{
					throw res;
				}
			}
		} catch (e) {
			throw e;
		}
	},
	/* 消息回执 */
	async receipt(conversation_id,msg_id,target_id,chat_type){
		try {
			if(chat_type == 'private'){
				let res = await uni.$api.chat.PrivateReceipt({conversation_id,msg_id,target_id})
				if(res){
					return true
				}else{
					throw res;
				}
			}else if(chat_type == 'group'){
				//群聊的未实现
				let res = await uni.$api.chat.GroupReceipt({conversation_id,msg_id,target_id})
				if(res){
					return true
				}else{
					throw res;
				}
			}
		} catch (e) {
			throw e;
		}
	},
	/* 消息离线获取 */
	async messageOffline({target_id,msg_id,select_type},chat_type){
		try {
			if(chat_type == 'private'){
				let res = await uni.$api.chat.PrivateMessageOffline({
					friend_id:target_id,
					msg_id,
					select_type
				})
				if(res){
					return res
				}else{
					return false
				}
			}else if(chat_type == 'group'){
				//群聊的未实现
				let res = await uni.$api.chat.groupMessageOffline({
					group_id:target_id,
					msg_id,
					select_type
				})
				if(res){
					return res
				}else{
					return false
				}
			}
		} catch (e) {
			throw e;
		}
	},
	/* 获取消息置顶 */
	async getTopMsg(target_id,chat_type){
		if(chat_type == 'private'){
			try {
				let res = await uni.$api.chat.getPrivateTopMsg({
					target_id
				})
				if(res){
					if(res.code == 200){
						let grouptop = {
							msg_id:res.data.msg_id,
							content_text:res.data.content_text,
							conversation_id:res.data.conversation_id,
							sender_id:res.data.sender_id,
							target_id:target_id,
							msg_type:res.data.msg_type,
						}
						$store.commit('setChatTopMsg', {
							data:grouptop,
							target_id:target_id
						})
						let myid = $store.state.user.user_info.user_id
						let storageTopMsg = uni.getStorageSync('chatPrivateTop') || {}
						if(!storageTopMsg[myid])storageTopMsg[myid] = {}
						storageTopMsg[myid][target_id] = grouptop
						uni.setStorageSync('chatPrivateTop',storageTopMsg)
						
					}else if(res.code == 2003){
						$store.commit('setChatTopMsg', {
							data:null,
							target_id:target_id
						})
						
						let myid = $store.state.user.user_info.user_id
						let storageTopMsg = uni.getStorageSync('chatPrivateTop') || {}
						if(!storageTopMsg[myid])storageTopMsg[myid] = {}
						if(storageTopMsg[myid] && storageTopMsg[myid][target_id]){
							storageTopMsg[myid][target_id] = null 
						}
						uni.setStorageSync('chatPrivateTop',storageTopMsg)
					}
					//存储本次打开缓存过的群id,受socket连接的影响
					$store.commit('setOpenPrivates',{uuid:target_id,type:'msgTop'})
					return res
				}else{
					return false
				}
			} catch (e) {
				throw e;
			}
		}else if(chat_type == 'group'){
			try {
				let res = await uni.$api.chat.getGroupTopMsg({
					target_id
				})
				if(res){
					if(res.code == 200){
						let grouptop = {
							msg_id:res.data.msg_id,
							content_text:res.data.content_text,
							conversation_id:res.data.conversation_id,
							sender_id:res.data.sender_id,
							target_id:target_id,
							msg_type:res.data.msg_type,
						}
						$store.commit('setChatTopMsg', {
							data:grouptop,
							target_id:target_id
						})
						let storageGroupTop = uni.getStorageSync('chatGroupTop') || {}
						storageGroupTop[target_id] = grouptop
						uni.setStorageSync('chatGroupTop',storageGroupTop)
						
					}else if(res.code == 2003){
						$store.commit('setChatTopMsg', {
							data:null,
							target_id:target_id
						})
						let storageGroupTop = uni.getStorageSync('chatGroupTop') || {}
						if(storageGroupTop[target_id]){
							storageGroupTop[target_id] = null
						}
						uni.setStorageSync('chatGroupTop',storageGroupTop)
					}
					//存储本次打开缓存过的群id,受socket连接的影响
					$store.commit('setOpenGroups',{group_id:target_id,type:'msgTop'})
					return res
				}else{
					return false
				}
			} catch (e) {
				throw e;
			}
		}
	},
	/* 消息置顶 */
	async topMsg({target_id,msg_id,is_top},chat_type){
		if(chat_type == 'private'){
			try {
				let res = await uni.$api.chat.topPrivateMsg({
					target_id,
					msg_id,
					is_top
				})
				if(res){
					return res
				}else{
					return false
				}
			} catch (e) {
				throw e;
			}
		}else if(chat_type == 'group'){
			try {
				let res = await uni.$api.chat.topGroupMsg({
					target_id,
					msg_id,
					is_top
				})
				if(res){
					return res
				}else{
					return false
				}
			} catch (e) {
				throw e;
			}
		}
	},
	//
	async msgEdit(chat_type,target_id,item){
		if(chat_type == 'private'){
			try{
				let res = await uni.$api.chat.privateMsgEdit({
					target_id:target_id,
					msg_type:item.msg_type,
					content_text:JSON.stringify(item.content_text),
					local_id:item.local_id,
					msg_id:item.msg_id
				})
				if(res){
					return res
				}else{
					return false
				}
			}catch(e){
				throw e;
			}
		}else if(chat_type == 'group'){
			try{
				let res = await uni.$api.chat.groupMsgEdit({
					target_id:target_id,
					msg_type:item.msg_type,
					content_text:JSON.stringify(item.content_text),
					local_id:item.local_id,
					msg_id:item.msg_id
				})
				if(res){
					return res
				}else{
					return false
				}
			}catch(e){
				throw e;
			}
		}
	}
}
const typeFunction = {
	text(data) {
		return new Promise((resolve, reject) => {
			resolve({
				...data,
				content_text: JSON.stringify(data.content_text)
			})
		})
	},
	b_c(data) {
		return new Promise((resolve, reject) => {
			resolve({
				...data,
				content_text: JSON.stringify(data.content_text)
			})
		})
	},
	image(data) {
		return new Promise(async (resolve, reject) => {
			try {
				//开始上传的时候赋值为0
				$store.dispatch('setProgress',{
					localId:data.local_id,
					index:0,
					percentage:0
				})
				let res = await upload.uploadFile(data.content_text[0].image.url, 'chat', 'image',(progress)=>{
					$store.dispatch('setProgress',{
						localId:data.local_id,
						index:0,
						percentage:progress.percent
					})
				})
				data.content_text[0].image.url = res.url
				data.content_text[0].image.thumb_url = ''
				resolve({
					...data,
					content_text: JSON.stringify(data.content_text)
				})
			} catch (e) {
				//上传失败赋值为-1
				$store.dispatch('setProgress',{
					localId:data.local_id,
					index:0,
					percentage:-1
				})
				//上传失败
				reject(e)
			} finally{
				$store.dispatch('deleteUploadGroup',data.local_id)
			}
		})
	},
	video(data) {
		return new Promise(async (resolve, reject) => {
			try {
				//开始上传的时候赋值为0
				$store.dispatch('setProgress',{
					localId:data.local_id,
					index:0,
					percentage:0
				})
				let res = await upload.uploadFile(data.content_text[0].video.url, 'chat', 'video',(progress)=>{
					$store.dispatch('setProgress',{
						localId:data.local_id,
						index:0,
						percentage:progress.percent
					})
				})
				data.content_text[0].video.url = res.url
				console.log(data.content_text[0].video);
				let imgres = await upload.uploadFile(data.content_text[0].video.thumb_url, 'chat', 'image')
				data.content_text[0].video.thumb_url = imgres.url || ''
				resolve({
					...data,
					content_text: JSON.stringify(data.content_text)
				})
			} catch (e) {
				//上传失败赋值为-1
				$store.dispatch('setProgress',{
					localId:data.local_id,
					index:0,
					percentage:-1
				})
				//上传失败
				reject(e)
			} finally{
				$store.dispatch('deleteUploadGroup',data.local_id)
			}
		})
	},
	audio(data) {
		return new Promise(async (resolve, reject) => {
			try {
				let res = await upload.uploadFile(data.content_text[0].audio.url, 'chat', 'audio')
				data.content_text[0].audio.url = res.url
				resolve({
					...data,
					content_text: JSON.stringify(data.content_text)
				})
			} catch (e) {
				//上传失败
				reject(e)
			}
		})
	},
	mixed(data) {
	    return new Promise(async (resolve, reject) => {
	        try {
	            const updatedContentText = await Promise.all(data.content_text.map(async (item,index) => {
	                if (item.video) {
	                    try {
							//开始上传的时候赋值为
							$store.dispatch('setProgress',{
								localId:data.local_id,
								index:index,
								percentage:0
							})
	                        const res = await upload.uploadFile(item.video.url, 'chat', 'video',(progress)=>{
								$store.dispatch('setProgress',{
									localId:data.local_id,
									index:index,
									percentage:progress.percent
								})
							});
							let imgres = await upload.uploadFile(item.video.thumb_url, 'chat', 'image')
	                        return {
	                            video: {
	                                ...item.video,
	                                url: res.url,
									thumb_url: imgres.url || ''
	                            }
	                        };
	                    } catch (e) {
							//上传失败赋值为-1
							$store.dispatch('setProgress',{
								localId:data.local_id,
								index:0,
								percentage:-1
							})
	                        // 处理失败情况
	                        return null;
	                    }
	                } else if (item.image) {
	                    try {
							//开始上传的时候赋值为
							$store.dispatch('setProgress',{
								localId:data.local_id,
								index:index,
								percentage:0
							})
	                        const res = await upload.uploadFile(item.image.url, 'chat', 'image',(progress)=>{
								$store.dispatch('setProgress',{
									localId:data.local_id,
									index:index,
									percentage:progress.percent
								})
							});
	                        return {
	                            image: {
	                                ...item.image,
	                                url: res.url,
									thumb_url: ''
	                            }
	                        };
	                    } catch (e) {
							//上传失败赋值为-1
							$store.dispatch('setProgress',{
								localId:data.local_id,
								index:0,
								percentage:-1
							})
	                        // 处理失败情况
	                        return null;
	                    }
	                }
	                return item; // 保持原有对象不变，如果不需要处理异常情况
	            }));
				// 过滤掉值为null的项
				const filteredContentText = updatedContentText.filter(item => item !== null);
	            // 将更新后的值赋给 data.content_text
	            data.content_text = filteredContentText;
				if(!data.content_text.length)reject('成功数据为空');
	            // resolve 更新后的数据
	            resolve({
	                ...data,
	                content_text: JSON.stringify(data.content_text)
	            });
	        } catch (error) {
	            reject(error);
	        } finally{
				$store.dispatch('deleteUploadGroup',data.local_id)
			}
	    });
	}
}